package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.IVerifycodeService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
@Slf4j
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 发送手机验证码
     * @param phone
     * @return
     */
    @Override
    public JsonResult sendSmsCode(String phone) {
        //1.校验手机验证码是否为空
        AssertUtil.isTrue(StringUtils.hasText(phone),"手机号不能为空");
        //2.手机号格式
        Pattern pattern = Pattern.compile("^1[3-9]{1}[0-9]{9}$");
        AssertUtil.isTrue(pattern.matcher(phone).find(),"手机号格式错误");
        //3.手机号必须是未注册的 openfegin调用Login服务

        //4.发送验证码
        String code = StrUtils.getRandomString(6);
        String msg = "您正在注册源码云课堂，验证码为:"+code+"请在5分钟类使用";
        if (redisTemplate.hasKey(phone)){
            //取出验证码的剩余时间
            Long expire = redisTemplate.getExpire(phone, TimeUnit.SECONDS);
            if (expire>240){
                return JsonResult.error("请勿重复发送消息");
            }else {
                String c = (String)redisTemplate.opsForValue().get(phone);
                log.info(c);//打印日志
                return JsonResult.me(code).setMessage(c);
            }
        }
        log.info(msg);//打印日志
        //设置验证码过期时间
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return JsonResult.me(code).setMessage(msg);
    }
}
